﻿<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script language="JavaScript" src="../../Comm/JScript.js" type="text/javascript"></script>
    <script type="text/javascript" src="../../Scripts/QueryString.js"></script>
    <script type="text/javascript" src="../../Scripts/config.js"></script>
    <script type="text/javascript" src="../../Comm/Gener.js"></script>
    <script src="../../Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script src="../../Scripts/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="../../Scripts/bootstrap/css/font-awesome.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/bootstrap/bootstrap-table/src/bootstrap-table.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/bootstrap-table/src/bootstrap-table.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/bootstrap/bootstrap-table/src/locale/bootstrap-table-zh-CN.js" type="text/javascript"></script>

     <!-- 引入用户要重写的公共js -->
    <script src="../../../DataUser/JSLibData/CCFormRef.js" type="text/javascript"></script>

    <style type="text/css">
        .row-margin-top
        {
            margin-top: 20px;
        }
        .search-margin
        {
            margin-top: 15px;
        }
    </style>
    <script type="text/javascript">
        var mapExt = null;
        //查询条件集合
        var condtionsArry = [];
        //查询条件，按照条件字段长度排序后
        var condtionFieldsArry = [];
        var mapExt = null;

        //初始化页面
        $(function () {

            var global = window;
            global.selectedRows = [];

            //获取MapExt信息
            var mypk = GetQueryString("MyPK");
            mapExt = new Entity("BP.Sys.MapExt", mypk);

            var webUser = new WebUser();

            //单选还是多选
            global.selectType = mapExt.GetPara("SelectType");

            //设置查询提示.
            var tip = mapExt.GetPara("SearchTip");
            $("#TB_Key").attr("placeholder", tip);

            //设置查询条件
            InitQueryParameters();

            //如果单选
            mapExt.ShowCheckBox = selectType == "0" ? false : true;

            //设置变量.
            global.FK_MapData = mapExt.FK_MapData;
            global.AttrOfOper = mapExt.AttrOfOper;
            global.oid = GetQueryString("OID");

            //获取列表的数据源
            var tableUrl = mapExt.Tag2;
            if (tableUrl == "") {
                alert('配置错误:查询数据源，初始化列表的数据源不能为空。');
                return;
            }

            // 初始化加载
            var frmEleDBs = new Entities("BP.Sys.FrmEleDBs");
            frmEleDBs.Retrieve("FK_MapData", FK_MapData, "EleID", AttrOfOper, "RefPKVal", oid);
            $.each(frmEleDBs, function (i, o) {
                global.selectedRows.push({
                    "No": o.Tag1,
                    "Name": o.Tag2
                });
            });

            global.searchTableColumns = [];

            global.searchTableColumns.push({
                field: "_checkbox",
                checkbox: true,
                formatter: function (value, row, index) {
                    if (row.checked) {
                        return {
                            "checked": true
                        };
                    }
                }
            });
            var columns = mapExt.Tag;
            //显示列的中文名称.
            if (typeof columns == "string") {
                $.each(columns.split(","), function (i, o) {
                    var exp = o.split("=");
                    var field;
                    var title;
                    if (exp.length == 1) {
                        field = title = exp[0];
                    } else if (exp.length == 2) {
                        field = exp[0];
                        title = exp[1];
                    }
                    if (!isLegalName(field)) {
                        return true;
                    }
                    searchTableColumns.push({
                        field: field,
                        title: title
                    });
                });
            } else {
                // by default
                searchTableColumns.push({
                    field: 'No',
                    title: '编号'
                });
                searchTableColumns.push({
                    field: 'Name',
                    title: '名称'
                });
            }


            var options = {
                striped: true,
                cache: false,
                sortOrder: "asc",
                strictSearch: true,
                minimumCountColumns: 2,
                highlightSelected: true,
                clickToSelect: true,
                singleSelect: !mapExt.ShowCheckBox,
                sortable: false,
                cardView: false,
                detailView: false,
                uniqueId: "No",
                columns: searchTableColumns
            };
            if (selectType == "0") {
                options.onCheck = function (row, element) {
                    removeAllSelectedData();
                    addSelectedData(global.selectedRows, [row]);

                };
                options.onUncheck = function (row, element) {
                    removeSelectedData(global.selectedRows, [row]);

                };

            } else {
                options.onCheck = function (row, element) {
                    addSelectedData(global.selectedRows, [row]);

                };
                options.onUncheck = function (row, element) {
                    removeSelectedData(global.selectedRows, [row]);

                };
                options.onCheckAll = function (rows) {
                    addSelectedData(global.selectedRows, rows);

                };
                options.onUncheckAll = function (rows) {
                    removeSelectedData(global.selectedRows, rows);

                };
            }

            $('#viewGrid').bootstrapTable(options);

            $("#TB_Key").on("keyup", function () {
                InputKeyWordData();
            });

            if (tableUrl.indexOf("@Key") > -1) {
                tableUrl = replaceAll(tableUrl, "@Key", "");
            }

            InputKeyWordData();
        });

        //查询列表、展示列表
        function loadViewGrid(gridUrl) {
            var global = window;

            /*
            $('#viewGrid').bootstrapTable("showColumn", "_checkbox");
            var searchTableColumns = [{
            field: "_checkbox",
            checkbox: true,
            formatter: function (value, row, index) {
            if (row.checked) {
            return {
            "checked": true,
            "disabled": row.disabled
            }
            }
            }
            }];*/

            // alert(gridUrl);

            var json = DBAccess.RunDBSrc(gridUrl); //执行url返回json.
            if ($.isArray(json)) {
                var selectedRows = window.selectedRows;
                if ($.isArray(selectedRows)) {
                    $.each(json, function (i, o) {
                        var sel = $.grep(selectedRows, function (obj) {
                            return o.No == obj.No;
                        });
                        if (sel.length > 0) {
                            o.checked = true;
                            //多选时才需要禁用已选
                            if (mapExt.ShowCheckBox == true) {
                                o.disabled = true;
                            }
                        }
                    });
                }
                $('#viewGrid').bootstrapTable("load", json);
            }
        }

        function isLegalName(name) {
            if (!name) {
                return false;
            }
            return name.match(/^[a-zA-Z\$_][a-zA-Z\d\$_]*$/);
        }

        function InitQueryParameters() {
            //$Para=Dept#Label=所在班级#ListURL=/DataUser/Handler.ashx?DoType=DtlImpReqAll
            var condtions = mapExt.Tag1;
            if (condtions == "")
                return;

            //组合查询条件数组
            var tempArry = condtions.split("$");
            $.each(tempArry, function (i, obj) {
                CondtionArryPush(obj);
            });

            //复制查询条件，排序
            condtionFieldsArry = jQuery.extend(true, [], condtionsArry);
            //利用js中的sort方法  
            condtionFieldsArry.sort(function (a, b) {
                return b.FieldKey.length - a.FieldKey.length;
            });
            //生成查询条件控件
            CreateCondtionCtrls();
        }

        //添加查询条件到数组
        function CondtionArryPush(condtion) {
            if (condtion == "") {
                return;
            }
            var paras = condtion.split("#");
            if (paras.length != 3) {
                return;
            }

            var item = {};
            var paraKey = "", labelText = "";
            var ctrType = "Date", ctrValue = "";
            $.each(paras, function (j, para) {
                if (para.indexOf("Para=") > -1) {
                    paraKey = para.replace("Para=", "");
                }
                if (para.indexOf("Label=") > -1) {
                    labelText = para.replace("Label=", "");
                }
                if (para.indexOf("ListURL=") > -1) {
                    ctrValue = para.replace("ListURL=", "");
                    ctrType = "ListURL";
                }
                if (para.indexOf("ListSQL=") > -1) {
                    ctrValue = para.replace("ListSQL=", "");
                    ctrType = "ListSQL";
                }
                if (para.indexOf("ListFuncName=") > -1) {
                    ctrValue = para.replace("ListFuncName=", "");
                    ctrType = "ListFuncName";
                }
                if (para.indexOf("EnumKey=") > -1) {
                    ctrValue = para.replace("EnumKey=", "");
                    ctrType = "EnumKey";
                }
                if (para.indexOf("DefVal=") > -1) {
                    ctrValue = para.replace("DefVal=", "");
                }
            });
            item.CtrlType = ctrType;
            item.FieldKey = paraKey;
            item.Label = labelText;
            item.Val = ctrValue;
            condtionsArry.push(item);
        }

        //根据条件数组生成查询控件
        function CreateCondtionCtrls() {
            //生成查询条件控件
            var searchPanel = $("#Search_Div");
            var groupItems = $.grep(condtionsArry, function (condtion) {
                return condtion.CtrlType == "ListURL" || condtion.CtrlType == "ListSQL" || condtion.CtrlType == "EnumKey";
            });
            //CreateGroupPanel(groupItems);

            //关键字后面的查询条件
            var noFirstRow = false;
            $.each(condtionsArry, function (i, condtion) {
                //第一行条件个数
                var countRow = 3;
                //如果不是第一行，条件的个数
                if (noFirstRow == true) {
                    countRow = 4;
                }
                if (i != 0 && !(i % countRow)) {
                    searchPanel.append("<br/><br/>");
                    noFirstRow = true;
                }

                //排除已创建分组条件
                var groupField = $("#HD_GroupField").val();
                if (groupField != "" && condtion.FieldKey == groupField) {
                    return;
                }

                var label = $("<label>" + condtion.Label + "</label>");
                label.addClass("searchpanellabel");
                searchPanel.append(label);
                switch (condtion.CtrlType) {
                    case "ListURL":
                    case "ListSQL":
                    case "ListFuncName":
                        var select = $("<select class='form-control' style='display:inline;width:120px;'></select>");
                        select.attr("id", condtion.FieldKey);
                        select.attr("name", condtion.FieldKey);
                        searchPanel.append(select);
                        var ifcData = DBAccess.RunDBSrc(condtion.Val);
                        if (ifcData && ifcData.length > 0) {
                            var oKeys = [];
                            for (var key in ifcData[0]) {
                                oKeys.push(key);
                            }
                            GenerBindDDL(condtion.FieldKey, ifcData, oKeys[0], oKeys[1], "");
                            $("#" + condtion.FieldKey).change(function () {
                                InputKeyWordData();
                            });
                        }
                        break;
                    case "EnumKey":
                        var select = $("<select class='form-control' style='display:inline;width:120px;'></select>");
                        select.attr("id", condtion.FieldKey);
                        select.attr("name", condtion.FieldKey);
                        searchPanel.append(select);
                        GenerBindEnumKey(condtion.FieldKey, condtion.Val, "");
                        $("#" + condtion.FieldKey).change(function () {
                            InputKeyWordData();
                        });
                        break;
                    default:
                        var defVal = condtion.Val;
                        defVal = defVal.replace('<br/>', '');
                        defVal = defVal.replace('@Now', "(new Date())");
                        defVal = new Date(eval(defVal));
                        defVal = FormatDate(defVal, "yyyy-MM-dd");
                        var inputDate = $("<input type='text'class='form-control' style='display:inline;width:120px;'/>");
                        inputDate.attr("id", condtion.FieldKey);
                        inputDate.attr("name", condtion.FieldKey);
                        inputDate.val(defVal);
                        searchPanel.append(inputDate);
                        $("#" + condtion.FieldKey).datepicker({
                            language: "zh-CN",
                            autoclose: true,
                            startView: 0,
                            format: "yyyy-mm-dd",
                            clearBtn: true,
                            todayBtn: false,
                            endDate: new Date()
                        }).on('changeDate', function (ev) {
                            InputKeyWordData();
                        });
                        return;
                }
            });

        }

        //输入关键字进行查询
        function InputKeyWordData() {
            var data = null;
            var UserNo = GetQueryString("UserNo");
            var RefPKVal = GetQueryString("RefPKVal");
            var keyWord = $("#TB_Key").val();
            var dbSrc = mapExt.Tag2;
            dbSrc = dbSrc.replace(/~/g, "'");
            var reg = new RegExp("@Key", "g");
            dbSrc = dbSrc.replace(reg, keyWord);
            dbSrc = DealExp(dbSrc);

            $.each(condtionFieldsArry, function (i, obj) {
                var regC = new RegExp("@" + obj.FieldKey, "g");
                var value = $("#" + obj.FieldKey).val();
                if (value == null || value == "null") value = "";
                dbSrc = dbSrc.replace(regC, value);
                if (mapExt.DBType == 0) {
                    if (dbSrc.toLowerCase().indexOf("where") == -1)
                        dbSrc = dbSrc + "WHERE 1=1";
                    if (value != "")
                        dbSrc = dbSrc + " and " + obj.FieldKey + "=" + value;
                }
            });


            loadViewGrid(dbSrc);

            //data = DBAccess.RunDBSrc(dbSrc, mapExt.DBType);

            //$("#jsonDataTable").html("");
            //if (data && data.length > 0) {
            //    InitTableByData(data);
            // }
        }

        function addSelectedData(globalSelectedRows, selectedRows) {
            if (!$.isArray(globalSelectedRows) || !$.isArray(selectedRows)) {
                return;
            }
            $.each(selectedRows, function (i, o) {
                var sel = $.grep(globalSelectedRows, function (obj) {
                    return obj.No == o.No;
                });
                if (sel.length == 0) {
                    SaveVal(FK_MapData, AttrOfOper, oid, o.No, o.Name);
                    globalSelectedRows.push(o);
                }
            });
        }
        function removeSelectedData(globalSelectedRows, selectedRows) {
            if (!$.isArray(globalSelectedRows) || !$.isArray(selectedRows)) {
                return;
            }
            $.each(selectedRows, function (i, o) {
                for (var index = 0; index < globalSelectedRows.length; index++) {
                    if (o.No == globalSelectedRows[index].No) {
                        Delete(AttrOfOper, oid, o.No);
                        globalSelectedRows.splice(index, 1);
                        break;
                    }
                }
            });
        }
        function removeAllSelectedData() {
            var globalSelectedRows = selectedRows;
            if (!$.isArray(globalSelectedRows) || !$.isArray(selectedRows)) {
                return;
            }
            for (var index = 0; index < globalSelectedRows.length; index++) {
                Delete(AttrOfOper, oid, globalSelectedRows[index].No);
            }
            selectedRows = [];
        }

        //删除数据.
        function Delete(keyOfEn, oid, No) {
            var frmEleDB = new Entity("BP.Sys.FrmEleDB");
            frmEleDB.MyPK = keyOfEn + "_" + oid + "_" + No;
            frmEleDB.Delete();
        }
        //设置值.
        function SaveVal(fk_mapdata, keyOfEn, oid, val1, val2) {
            var frmEleDB = new Entity("BP.Sys.FrmEleDB");
            frmEleDB.MyPK = keyOfEn + "_" + oid + "_" + val1;
            frmEleDB.FK_MapData = fk_mapdata;
            frmEleDB.EleID = keyOfEn;
            frmEleDB.RefPKVal = oid;
            frmEleDB.Tag1 = val1;
            frmEleDB.Tag2 = val2;
            if (frmEleDB.Update() == 0) {
                frmEleDB.Insert();
            }
        }

    </script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-9 col-sm-9" style="width:99%">
                        <div class="pull-center search search-margin" id="Search_Div" style="width:100%">
                            <label>关键字</label>
                            <input class="form-control" style="display:inline;width:240px;" type="text" placeholder="" id="TB_Key">
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
        <div class="row row-margin-top">
            <div class="col-md-4 col-sm-4" id="viewGrid_Panel" style="width:99%">
                <table id="viewGrid" style></table>
            </div>
        </div>
    </div>
</body>
</html>
